<?php
// +----------------------------------------------------------------------
// | QbtCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.qbt8.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 千佰特 <http://www.qbt8.com>
// +----------------------------------------------------------------------
namespace plugins\qbt_payment_management\controller;

use think\Controller;
use think\Db;
vendor("pay.wxpay.lib.WxPay#Api");
vendor("pay.wxpay.example.WxPay#JsApiPay");
vendor("pay.wxpay.example.WxPay#NativePay");
vendor("pay.wxpay.example.log");
vendor("pay.wxpay.example.WxPay#Config");
vendor("pay.wxpay.lib.WxPay#Notify");
class WxPayController extends Controller
{

    /**微信支付-统一下单
     * @param $openId 微信用户openid
     * @param $order 唯一订单号
     * @param $money 订单额度
     * @param $url 回调地址
     * @param $body 备注说明
     * @param $Trade_type 微信支付方式
     * @return \json数据，可直接填入js函数作为参数|string
     * @throws \WxPayException
     */
    public function pay($data){
        //默认回调地址
        !empty($data['url'])?$url = $data['url']: $url = 'http://'.$_SERVER['SERVER_NAME'].cmf_plugin_url('QbtPaymentManagement://WxPay/notify');
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($data['body']);
        $input->SetOut_trade_no($data['order']);
        $input->SetTotal_fee($data['money']*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url($url);
        $input->SetTrade_type($data['Trade_type']);
        if (!empty($data['openid'])){
            $input->SetOpenid($data['openid']);
        }
        if (!empty($data['product_id'])){
            $input->SetProduct_id($data['product_id']);
        }
        if ($data['Trade_type']=='NATIVE') {
            $notify = new \NativePay();
            $order = $notify->GetPayUrl($input);
        }else{
            $config = new \WxPayConfig();
            $order = \WxPayApi::unifiedOrder($config, $input);
        }
        if ($order['return_code']=='SUCCESS' && $order['result_code']=='SUCCESS'){
            if ($data['Trade_type']=='JSAPI') {
                $tools = new \JsApiPay();
                $jsApiParameters = $tools->GetJsApiParameters($order);
                return $jsApiParameters;
            }
            return json_encode($order);
        }else{
            return -1;
        }
    }

    /**支付回调
     * @throws \WxPayException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function notify()
    {
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $xmlObj = simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA);
        $xmlArr = json_decode(json_encode($xmlObj),true);
        $result_code = $xmlArr['result_code'];
        $transaction_id =  $xmlArr['transaction_id'];
        if($result_code == 'SUCCESS'){          
            //查询订单支付情况，并标注支付
            $this->orderquery($transaction_id);
        }
    }

    /** 查询支付状态
     * @param $transaction_id 微信支付订单号
     * @return bool
     * @throws \WxPayException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function orderquery($transaction_id){
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $config = new \WxPayConfig();
        $result = \WxPayApi::orderQuery($config, $input);
        //添加支付日志
        if(array_key_exists("return_code", $result) && $result["return_code"] == "SUCCESS")
        {
            //添加支付日志
            $data['money'] = $result["total_fee"]/100;
            $data['pay_time'] = strtotime($result["time_end"]);
            $data['pay_type'] = 1;
            $data['transaction_id'] = $result["transaction_id"]; //微信支付单号
            $data['order_no'] = $result["out_trade_no"]; //商户订单号
            $data['trade_type'] = $result["trade_type"]; //交易类型

            DB::name('payment_log')->insert($data);

            //修改订单状态

            //通知微信服务器
            echo exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
        }
        return false;
    }
}
